<script setup lang="ts">
import type { WordWithStatus } from '@/pages/wordStudy/type'
import { handleApiError, studentApi } from '@/api'
import NavBar from '@/components/NavBar/index.vue'
import { useStudyParams } from '@/composables/useStudyParams'
import { WordDegree } from '@/enums/word'
import { useCurrentStudentInfoStore } from '@/stores/modules/useCurrentStudentInfoStore'
import { useUnitStudyWordsStore } from '@/stores/modules/useUnitStudyWordsStore'
import { dialog } from '@/utils/dialog'
import { redirectTo } from '@/utils/navigation'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import AfterCheckWord from './components/AfterCheckWord.vue'
import ExitDialog from './components/ExitDialog.vue'
import HeaderTips from './components/HeaderTips.vue'
import UnfinishedDialog from './components/UnfinishedDialog.vue'

const studentInfoStore = useCurrentStudentInfoStore()
const unitStudyWordsStore = useUnitStudyWordsStore()
const maxWords = 3
const minWords = 2
// 单词数量必须是5的倍数
const multipleWords = 5
const words = ref<WordWithStatus[]>([])
const exitDialogRef = ref()
const unfinishedDialogRef = ref()
const urlParams = ref({
  type: '',
  courseId: 0,
  unitNo: 99,
})

const { initStartTime, setStudyParams } = useStudyParams(words)

const selectedWords = computed(() => words.value.filter(w => w.known === false).length)
// 已选单词全部为已会
const isAllKnown = computed(() => words.value.every(w => w.known === true))

const title = computed(() => {
  if (urlParams.value.type === 'practiceReview') {
    return '陪练复习'
  }
  return '复习'
})

function leftClick() {
  exitDialogRef.value.openDialog()
}

async function onConfirm() {
  if (selectedWords.value < minWords) {
    dialog.show({
      title: '提示',
      contentTitle: `选词数量未达到${minWords}个`,
      contentSubTitle: `再选几个单词吧，凑成${multipleWords}的倍数记忆效果更好`,
      buttons: [
        {
          text: '继续选词',
          type: 'primary',
          onClick: () => {
            console.log('点击了确定')
          },
        },
      ],
    })
    return
  }

  //   大于15个单词且不是5的倍数，存在单词未选择时，提示
  if (selectedWords.value > maxWords && selectedWords.value % multipleWords !== 0) {
    dialog.show({
      title: '提示',
      contentTitle: `选词数量建议是${multipleWords}的倍数`,
      contentSubTitle: `再选几个单词吧，凑成${multipleWords}的倍数记忆效果更好`,
      buttons: [
        {
          text: '继续选词',
          type: 'primary',
          onClick: () => {
            console.log('点击了确定')
          },
        },
      ],
    })
    return
  }

  // 已选单词全部为已会，提示
  if (isAllKnown.value) {
    dialog.show({
      title: '提示',
      contentTitle: '全部都会啦，不需要再识记啦~',
      contentSubTitle: '经鉴定，学富五车，才高八斗！',
      buttons: [
        {
          text: '返回',
          type: 'primary',
          onClick: () => {
            uni.navigateBack()
          },
        },
      ],
    })
  }

  const preStudyParams = {
    studentId: studentInfoStore.studentId,
    lessonId: studentInfoStore.lessonId,
    courseId: urlParams.value.courseId,
    unitNo: urlParams.value.unitNo,
    words: words.value.map(w => ({
      wordId: w.wordId,
      degree: w.known ? WordDegree.KNOWN : WordDegree.UNKNOWN,
    })),
  }

  const [error] = await studentApi.preStudy(preStudyParams)

  if (error) {
    return handleApiError(error)
  }

  if (urlParams.value.type === 'practiceReview') {
    unitStudyWordsStore.switchToReview()
    unitStudyWordsStore.startStudyWords({
      studentId: studentInfoStore.studentId,
      lessonId: studentInfoStore.lessonId,
      courseId: urlParams.value.courseId,
      unitNo: urlParams.value.unitNo,
    })
    return
  }

  redirectTo({
    url: '/pages/wordStudy/reviewReport',
    params: {
      studentId: studentInfoStore.studentId,
      lessonId: studentInfoStore.lessonId,
    },
  })
}

function onWordClick(word: WordWithStatus) {
  word.clickNum = (word.clickNum || 0) + 1
}

function onUnfinishedConfirm() {
  console.log('用户已确认未完成提示')
}

function formatWords(words: WordWithStatus[]) {
  return words.map(w => ({
    ...w,
    known: null,
  }))
}

async function loadWords() {
  const [error, result] = await studentApi.getWordReviewRecommend({
    studentId: studentInfoStore.studentId,
    lessonId: studentInfoStore.lessonId,
  })
  if (error) {
    return handleApiError(error)
  }
  words.value = formatWords(result.data.words as unknown as WordWithStatus[])
}

onLoad((options) => {
  urlParams.value.type = options?.type
  urlParams.value.courseId = options?.courseId
  urlParams.value.unitNo = options?.unitNo

  loadWords()
  initStartTime()
  setStudyParams({
    studentId: studentInfoStore.studentId,
  })
})
</script>

<template>
  <view class="after-check">
    <NavBar :title="title" @left-click="leftClick" />
    <HeaderTips>3秒内不认识的单词，标记为不会，系统将帮助你记忆巩固哦</HeaderTips>

    <ExitDialog ref="exitDialogRef" />
    <UnfinishedDialog ref="unfinishedDialogRef" @confirm="onUnfinishedConfirm" />

    <AfterCheckWord
      :words="words"
      @on-confirm="onConfirm"
      @word-click="onWordClick"
    />
  </view>
</template>

<style lang="scss" scoped>
.after-check{
    padding-bottom: 120rpx;
}
</style>
